<?php
function addbook()
{
//连接数据库
    $dsn = 'mysql:dbname=books;host=localhost';
    $user = 'root';
    $password = '123456';
    try {
        $db = new PDO($dsn, $user, $password);

        do {
            //获取用户信息
            echo "请输入图书编号：";
            $bookid = trim(fgets(STDIN));

            // 图书编号存在，重新输入
            //重新输入3次，结束办理！
            $count = 3;
            while ($db->query("select bookid from book where  bookid = '$bookid'")->fetch()) {

                echo "图书已存在，请重新输入：";
                $bookid = trim(fgets(STDIN));
                echo "\n";
                if ($count-- == 1) {

                    echo "已输入3次，结束办理！\n";
                    echo "返回首页\n";
                    echo "\n";

                    //调用bookLogin类中moshi()方法
                    $login = new bookLogin();
                    $login->moshi();
                    break;
                }
            }


            echo "请输入图书名称：";
            $bookName = trim(fgets(STDIN));
            echo "请输入出版社：";
            $press = trim(fgets(STDIN));
            echo "请输入价格：";
            $price = (int)fgets(STDIN);


            //用户信息核实
            echo "你需要办理的开卡信息：\n";
            echo "\n";
            echo '图书编号：' . $bookid . "\n";
            echo '图书名称：' . $bookName . "\n";
            echo '出版社：' . $press . "\n";
            echo '价格：' . $price . "\n";
            echo "\n";
            echo "输入y确认，任意键重新输入：";
            $re = trim(fgets(STDIN));
            $re = strtolower($re);
        } while ($re != 'y');

        //添加用户信息数组
        $sqlAdd = $db->prepare("insert into book (bookid,bookName,press,price) values(:bookid,:bookName,:press,:price)");
        $sqlAdd->execute([
            ':bookid' => $bookid,
            ':bookName' => $bookName,
            ':press' => $press,
            ':price' => $price
        ]);

        //获取影响行数
        $row = $sqlAdd->rowCount();

        //返回影响行数
        //如果影响行数大于等于1，则判断成功，否则失败
        if ($row >= 1) {
            echo "添加成功，受影响的行: 1";
            echo "\n";

            //提示开卡成功
            echo "书籍入库成功！\n";

        } else {
            echo "添加失败！\n";
            echo "\n";
            echo "书籍入库失败！";
            echo "\n";
        }
        echo "\n";
        
    } catch (PDOException $e) {
        echo 'Connection failed:' . $e->getMessage();
    }

}